package cn.hftoday.util;

import java.util.*;
import java.security.*;

/**
 * String parse functions
 * @author lane.cn@gmail.com
 */
public abstract class StringParser {
	
	/**
	 * invalid string
	 */
	public static final String INVALID_STRING = "n/a";
	
	/**
	 * escape char in HTML document
	 * @param s
	 * @return
	 */
	public static String parseHtml(String s) {
		s = s.replaceAll("<", "&lt;");
		s = s.replaceAll(">", "&gt;");
		s = s.replaceAll("\"", "&quot;");
		s = s.replaceAll("\r\n", "<br>");
		s = s.replaceAll("\r", "<br>");
		s = s.replaceAll("\n", "<br>");
		return s;
	}
	
	/**
	 * remove HTML tags
	 * @param s
	 * @return
	 */
	public static String removeHtmlTag(String s) {
		s = s.replaceAll("<[^>]*>", " ");
		s = s.replaceAll("&nbsp;", " ");
		s = s.replaceAll("&quot;", " ");
		s = s.replaceAll("&apos;", " ");
		s = s.replaceAll("&lt;", " ");
		s = s.replaceAll("&gt;", " ");
		return s;
	}
	
	/**
	 * escape char in XML document
	 * @param s
	 * @return
	 */
	public static String parseXml(String s) {
		s = s.replaceAll("<", "&lt;");
		s = s.replaceAll(">", "&gt;");
		s = s.replaceAll("\"", "&quot;");
		return s;
	}
	
	/**
	 * escape char in SQL statement, and truncate string
	 * @param s
	 * @param length
	 * @return
	 */
	public static String parseSql(String s, int length) {
		if (length > 0) {
			//truncate string when length gt zero
			/*if (containsChineseWord(s)) {
				length = length / 3;
			}
			deleted. store data in UTF-8 format
			*/
			if (s.length() > length) {
				s = s.substring(0, length);
			}
		}
		
		//escape char in SQL
		s = s.replaceAll("'", "''");
		s = s.replaceAll("\\\\", "\\\\\\\\");
		return s;
	}

	/**
	 * escape char in SQL statement
	 * @param s
	 * @return
	 */
	public static String parseSql(String s) {
		s = s.replaceAll("'", "''");
		s = s.replaceAll("\\\\", "\\\\\\\\");
		return s;
	}

	/**
	 * contains chinses word
	 * @param s
	 * @return
	 */
	/*
    public static boolean containsChineseWord(String s) {
        char[] a = s.toCharArray();
        for (int i = 0; i < a.length; i ++) {
            if (a[i] > 255) {
                return true;
            }
        }
        return false;
    }
    */

    /**
	 * get value from name-value pair
	 * example: "a=b;c=d;e=f"
	 * String value = StringPrser.getValue("c", "a=b;c=d;e=f");
	 * now value is "d"
	 * @param name
	 * @param s
	 * @return
	 */
	public static String getValue(String name, String s) {
		String[] ary = s.split(";");
		for (int i = 0; i < ary.length; i ++) {
			String nvp = ary[i].trim();
			String[] ary2 = nvp.split("=");
			String n = ary2[0].trim();
			String v = ary2[1].trim();
			v = v.replaceAll("%eq%", "=");
			v = v.replaceAll("%col%", ";");
			if (n.equals(name)) {
				return v;
			}
		}
		return null;
	}

	/**
	 * truncate string from right side
	 * @param s
	 * @param length
	 * @return
	 */
	public static String right(String s, int length) {
		if (length >= s.length()) {
			return s;
		}
		return (s.substring(s.length() - length));
	}

	/**
	 * truncate string from left side
	 * @param s
	 * @param length
	 * @return
	 */
	public static String left(String s, int length) {
		if (length >= s.length()) {
			return s;
		}
		return s.substring(0, length);
	}
	
	/**
	 * format sql string
	 * @param format
	 * @param args
	 * @return
	 */
	public static String formatSql(String format, String ...args) {
		String s = format;
		for (int i = 0; i < args.length; i++) {
			if (args[i] == null)
				s = s.replaceAll("\\{" + i + "\\}", "");
			else
				s = s.replaceAll("\\{" + i + "\\}", parseSql(args[i]).replaceAll("\\\\", "\\\\\\\\"));
		}
		return s;
	}

	/**
	 * format string
	 * @param format
	 * @param args
	 * @return
	 */
	public static String format(String format, String ...args) {
		String s = format;
		for (int i = 0; i < args.length; i++) {
			if (args[i] == null)
				s = s.replaceAll("\\{" + i + "\\}", "");
			else
				s = s.replaceAll("\\{" + i + "\\}", args[i]);
		}
		return s;
	}

	/**
	 * format number to money format
	 * @param f
	 * @return
	 */
	/*
	public static String moneyFormat(float f)
	{
		float f2 = f * 100;
		int i = (int)(f2 + 0.5);
		if (f2 < 0) {
			i = (int)(f2 - 0.5);
		}
		f2 = (float)i / 100;
		String s = Float.toString(f2);
		if (s.startsWith(".")) {
			s = "0" + s;
		}
		if (s.indexOf('.') < 0) {
			s += ".00";
		}
		else if (s.indexOf('.') == s.length() - 2) {
			s += "0";
		}
		return s;
	}
	*/
	
	/**
	 * md5 digest
	 * @param s
	 * @return
	 */
	public static String md5(String s) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(s.toString().getBytes());
			byte[] b = md.digest();
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < b.length; i ++) {
				int val = ((int)b[i]) & 0xff;
				if (val < 16) sb.append("0");
				sb.append(Integer.toHexString(val));
			}
			return sb.toString();
		} catch (Exception e) {
			throw new RuntimeException("error.md5");
		}
	}
	
	/**
	 * fill chars on left side
	 * @param s
	 * @param chars
	 * @return
	 */
	public static String padLeft(String s, String chars) {
		int iLength = chars.length();
		if (iLength > s.length()) {
			String r = chars.substring(0, iLength - s.length()) + s;
			return r;
		} else {
			return s.substring(s.length() - iLength);
		}
	}
	
	public static String[] split(String s, char delimiter, char quoter) {
		if (s.indexOf(delimiter) < 0) {
			return new String[] {s};
		}
		
		int length = s.length();
		//System.out.println("LENGTH *********** " + length);
		boolean inQuoter = false;
		List<Integer> positions = new ArrayList<Integer>();
		for (int i = 0; i < length; i ++) {
			char c = s.charAt(i);
			if (c == quoter) {
				inQuoter = !inQuoter;
			}
			else if (c == delimiter && !inQuoter) {
				positions.add(new Integer(i));
				//System.out.println("ADD POS *********** " + i);
			}
		}
		
		if (positions.size() == 0) {
			return new String[] {s};
		}
		
		int count = positions.size();
		String[] r = new String[count + 1];
		r[0] = s.substring(0, positions.get(0).intValue());
		//System.out.println("R *********** " + r[0]);
		for (int i = 0; i < count; i ++) {
			if (i == count - 1) {
				r[i + 1] = s.substring(positions.get(i).intValue() + 1);
			}
			else {
				r[i + 1] = s.substring(positions.get(i).intValue() + 1, positions.get(i + 1).intValue());
			}
			//System.out.println("R *********** " + r[i + 1]);
		}
		return r;
	}

}
